# -*- coding: utf-8 -*-
import json
import random
import logging
from datetime import datetime, timedelta

from common.campaign.model.wheel import *
from common.campaign.db import wheel as wheel_db
from common.account.db import account as account_db
from common.stats import MG_BIGBANG_COLL as mg

from common.cache import redis_cache

from common.utils.tz import local_now, utc_to_local
from common.utils import exceptions as err

from django.conf import settings

_LOGGER = logging.getLogger('campaign')


def _choose_award(user_id):
    user_stats = mg.user_stats.find_one({"_id": user_id}) or {}
    recharge = user_stats.get('recharge', {}).get('total', 0)
    if recharge < 2:
        index = random.choice([0, 1])
        return index
    rand_int = random.randint(1, 100)
    index = 0
    for ratio_item in AWARD_RATIO:
        if ratio_item['start'] <= rand_int <= ratio_item['end']:
            return index
        index += 1
    return 0


def single_play(user_id):
    """
    转一次
    """
    date_str = local_now().strftime('%Y-%m-%d')
    award_index = _choose_award(user_id)
    award_item = wheel_db.play_wheel(user_id, date_str, award_index)
    redis_cache.add_new_fortune(user_id, award_index)
    _LOGGER.info('fortune wheel, %s awarded %s, is_double:%s', user_id, award_index, award_item.is_double)
    return award_index, award_item.is_double


def get_status(user_id):
    """
    获取当天参与情况，包括任务完成情况和参与次数
    从cache刷新至db
    """
    data = {}
    date_str = local_now().strftime('%Y-%m-%d')
    current_status = redis_cache.get_wheel_task(user_id)
    item = wheel_db.fresh_wheel(user_id, date_str, current_status)
    data.update({
        'left_normal_times': item.left_normal_times,
        'left_double_times': item.left_double_times,
        'apply_normal_times': item.apply_normal_times,
        'apply_double_times': item.apply_double_times,
        'task_status': item.task_status,
    })
    return data


def _choose_task():
    rand_int = random.randint(1, 100)
    for ratio_item in DOUBLE_RATIO:
        if ratio_item['start'] <= rand_int <= ratio_item['end']:
            return ratio_item['bit']
    return 0


def random_double_bit():
    """
    随机第二天的双倍任务
    """
    date_str = (local_now() + timedelta(1)).strftime('%Y-%m-%d')
    rand_bit = _choose_task()
    redis_cache.set_double_bit(date_str, rand_bit)
    _LOGGER.info('random_double_bit, bit:%s, date:%s', rand_bit, date_str)
    return date_str, rand_bit


def get_timeline():
    a_list = []
    items = redis_cache.get_fortune_timeline()
    uids = []
    for item in items:
        user_id, award_index = item.split(':')
        user_id = int(user_id)
        award_index = int(award_index)
        award_name = AWARD_RATIO[award_index]['name']
        uids.append(user_id)
        a_list.append({
            'user_id': user_id,
            'award_index': award_index,
            'award_name': award_name
        })
    accounts = account_db.get_account_in_ids(uids)
    accounts = dict([(account.id, account.user_name) for account in accounts])
    for a in a_list:
        user_name = accounts.get(a['user_id'])
        if user_name:
            a['nick_name'] = user_name[0] + '***' + user_name[-1]
    return a_list


_DEFAULT_PAGE_SIZE = 20


def get_user_award(user_id, page, size):
    limit = _DEFAULT_PAGE_SIZE if not size or size > _DEFAULT_PAGE_SIZE else size
    if not page or page < 1:
        page = 1
    offset = 0 if not page else (page - 1) * limit
    a_list = []
    items = wheel_db.get_user_award(user_id, limit, offset)
    for item in items:
        award_name = AWARD_RATIO[item.award_index]['name']
        a_list.append({
            'award_time': utc_to_local(item.created_at).strftime('%Y-%m-%d %H:%M:%S'),
            'award_index': item.award_index,
            'award_name': award_name,
            'status': item.status
        })
    return a_list


def add_wheel_task(user_id, price):
    if price >= 100:
        redis_cache.add_wheel_task(user_id, 1)
    if price >= 200:
        redis_cache.add_wheel_task(user_id, 2)
    if price >= 500:
        redis_cache.add_wheel_task(user_id, 4)
    if price >= 1000:
        redis_cache.add_wheel_task(user_id, 8)
